/**
 * 
 */
package Pursuit_Client;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import Pursuit_Server.server;

/**
 * @author Duyun Chen
 *
 */

public class PursuitServer extends OutputStream implements Runnable 
{
	private String[] opts;	//options given to server
	private Thread thread = new Thread(this);
	private final String serverOutputPrefix = "[SERVER] ";
	private PursuitServerConsole console = new PursuitServerConsole();
	
	public PursuitServer(String[] in) 
	{
		super();
		
		//direct all output from server into custom printstream (PursuitClient)
		System.setOut(new PrintStream(this));
		//System.setErr(new PrintStream(this));
		
		//set command-line parameters
		opts = in;
	}
	
	public void run() {	//implements Runnable
    	try 
    	{	
    		server.main(opts); //run server with given commandline options
    	} 
    	catch (Exception e) {	PursuitClient.print(e.getMessage());	}	
	}
	
	public void start() 
	{		
		if (!thread.isAlive()) 
				thread.start();
		console.setVisible(true);
	}
	
	@Override	
	public void write(byte[] b) 
	{
		String out = new String(b);
		if (out.endsWith("\n")) out = out.substring(0, out.length() - 2); //remove endline char
		console.print(serverOutputPrefix + out);
	}
	
	@Override	
	public void write(byte[] b, int off, int len) 
	{
		String out = new String(b, off, len);
		if (out.endsWith("\n")) out = out.substring(0, out.length() - 2); //remove endline char
		console.print(serverOutputPrefix + out);
	}
	
	@Override
	public void write(int arg0) throws IOException 
	{
		//not needed technically but is required for abstract class extension
	}
}
